<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('account.resetPassword')"
    custom-class="dialog-min-width"
    :width="500"
    :destroy-on-close="true"
  >
    <el-form
      v-loading="loading"
      ref="formRef"
      :model="formEdit"
      :rules="rules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="24">
          <el-alert
            :title="t('account.passwordWarning')"
            type="warning"
            :closable="false"
          /><br />
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="t('account.password')" prop="password2">
            <el-input
              v-model="state.password1"
              :type="type1"
              @focus="type1 = 'password'"
              show-password
              minlength="8"
              maxlength="16"
              autocomplete="new-password"
              clearable
              onkeypress="capsLockOn($event)"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            :label="t('account.confirmPassword')"
            prop="password2"
            :class="store.appLocale == 'en_US' ? 'break-label' : ''"
          >
            <el-input
              v-model="state.password2"
              :type="type2"
              @focus="type2 = 'password'"
              show-password
              minlength="8"
              maxlength="16"
              autocomplete="new-password"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">{{
          t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{
          t("common.submitButton")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { useStore } from "../../../stores/store";
import utils from "../../../utils/utils";
import apiAccount from "../api/account";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });

const store = useStore();
const loading = ref(false);
const formRef = ref();
const publicKey = ref("");
const type1 = ref("");
const type2 = ref("");

const stateOriginal = () =>
  reactive({
    dialogFormVisible: false,
    password1: "",
    password2: "",
  });
const state = reactive(stateOriginal());

const formEdit = reactive({
  sessionId: "",
  accountId: "",
});

const rules = reactive({
  password1: [
    {
      validator: (rule: any, value: any, callback: any) => {
        // console.log("password1 validator", value);
        // 由于 password1 未绑定到 formEdit 所以 value 取不到值，直接使用 state.password1
        if (state.password1 === "") {
          callback(new Error(t("common.required")));
        } else {
          callback();
        }
      },
      trigger: "blur",
      required: true,
    },
  ],
  password2: [
    {
      validator: (rule: any, value: any, callback: any) => {
        // console.log("password2 validator", value);
        if (state.password2 === "") {
          callback(new Error(t("common.required")));
        } else if (state.password2 !== state.password1) {
          callback(new Error(t("account.passwordInconsistent")));
        } else {
          callback();
        }
      },
      trigger: "blur",
      required: true,
    },
  ],
});

const emit = defineEmits<{
  (event: "on-submit-success", row: any): void;
}>();

const handleSubmit = async () => {
  // 处理业务逻辑，触发关闭事件
  await formRef.value.validate();

  // 加密数据，清理原文
  let encryptedPassword = utils.doSm2Encrypt(publicKey.value, state.password1);
  // 修改密码
  apiAccount
    .changeAccountPassword(
      formEdit.sessionId,
      formEdit.accountId,
      encryptedPassword
    )
    .then((response: any) => {
      loading.value = false;
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", formEdit);
      }
    })
    .catch((err: any) => {
      loading.value = false;
      utils.errorNotification(t("common.submitException"), err);
    });
};

const getPublicKey = () => {
  formEdit.sessionId = utils.getUUID();
  apiAccount
    .generateSessionPublicKeyQ(formEdit.sessionId)
    .then((response: any) => {
      if (response.data.code == 200) {
        publicKey.value = response.data.data;
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = (row: any) => {
  // console.log("show", row);
  Object.assign(state, stateOriginal());
  Object.assign(formEdit, row);
  getPublicKey();
  state.dialogFormVisible = true;
};

defineExpose({
  show,
});
</script>
